package com.example.petstoreservice.controller;

import com.example.petstoreservice.entity.CreateOrderRequest;
import com.example.petstoreservice.entity.Order;
import com.example.petstoreservice.entity.OrderItems;
import com.example.petstoreservice.entity.Result;
import com.example.petstoreservice.service.OrderService;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    @GetMapping("/all")
    public Result<List<Order>> getAllOrders(){
        Result<List<Order>> result = new Result<>();
        List<Order> orders = orderService.getAllOrders();

        // 遍历订单列表，将 orderId 转换为 String 类型
        for (Order order : orders) {
            order.setOrderIdString(String.valueOf(order.getOrderId()));
        }

        result.setData(orders);
        return result;
    }

    @PostMapping("/insertOrder")
    public Result<?> insertOrder(@RequestBody Order order){
        if(orderService.insertOrder(order)){
            return Result.success("订单添加成功");
        }else{
            return Result.fail("订单添加失败!");
        }
    }

    @PostMapping("/createOrder")
    public Result<String> createOrder(@RequestBody CreateOrderRequest request) {
        Result<String> res = new Result<>();
        BigDecimal couponDiscount = request.getCouponDiscount(); // 注意 BigDecimal 类型
        Long success = orderService.createOrder(request.getUsername(), request.getOrderDataList(), request.getStatus(), request.getAddressId(), couponDiscount);
        if (success == 0L) {
            return Result.fail("你没有选择商品");
        } else if (success == -1L) {
            return Result.fail("商品库存不足");
        } else {
            res.setData(String.valueOf(success));  // 将 Long 转为 String 返回
            res.setStatusCode("200");
            return res;
        }
    }
    @PostMapping("/refund")
    public Result<?> refund(@RequestBody Map<String, Object> payload){
        Long orderId = Long.parseLong(payload.get("orderId").toString());
        String info =payload.get("info").toString();
        if(orderService.refund(orderId,info)){
            return Result.success("退单申请成功!");
        }else{
            return Result.fail("退单申请失败!");
        }

    }

    @PostMapping("/updateOrder")
    public Result<?> updateOrder(@RequestBody Order order){
        Long orderId = order.getOrderId();
        Order existingOrder = orderService.getOrderById(orderId);
        if(existingOrder == null) {
            return Result.fail("当前订单不存在");
        }

        // Check and update each field individually to avoid clearing others
        if(order.getTotal() != null) {
            existingOrder.setTotal(order.getTotal());
        }
        if(order.getStatus() != null) {
            existingOrder.setStatus(order.getStatus());
        }
        if(order.getInfo() != null) {
            existingOrder.setInfo(order.getInfo());
        }
        if(order.getAddressId() != null) {
            existingOrder.setAddressId(order.getAddressId());
        }

        // Update the order in the database
        if(orderService.updateOrder(existingOrder)){
            return Result.success("订单更新成功!");
        } else {
            return Result.fail("订单更新失败!");
        }
    }

    @GetMapping("/delete/{orderId}")
    public Result<?> deleteOrder(@PathVariable Long orderId){
        if(orderService.deleteOrder(orderId)){
            return Result.success("订单删除成功!");
        }else{
            return Result.fail("订单删除失败!");
        }
    }

    @GetMapping("/{orderId}")
    public Result<Order> getOrderById(@PathVariable Long orderId){
        Result<Order> result = new Result<>();
        Order order = orderService.getOrderById(orderId);
        if(order != null){
            result.setData(order);
            result.setStatusCode("200");
        }else{
            return Result.fail("未查询到当前订单");
        }
        return result;
    }
    @GetMapping("/getOrder/{username}/{status}")
    public Result<List<Order>> getOrderByUsernameAndStatus(@PathVariable String username,@PathVariable String status){
        Result<List<Order>> res=new Result<>();
        List<Order> orderList=orderService.getOrderByUsernameAndStatus(username,status);
        if(orderList!=null){
            res.setData(orderList);
            res.setStatusCode("200");
            return res;
        }else{
            return Result.fail("当前没有相关订单");
        }
    }

    @GetMapping("/user/{username}")
    public Result<List<Order>> getOrdersByUsername(@PathVariable String username) {
        Result<List<Order>> result = new Result<>();
        List<Order> orders = orderService.getOrdersByUserName(username);
        if(orders != null && !orders.isEmpty()){
            // 遍历所有订单项，将 orderId 转换为字符串类型
            for (Order order : orders) {
                if (order.getOrderId() != null) {
                    order.setOrderIdString(String.valueOf(order.getOrderId())); // 使用新的字段保存字符串类型的 orderId
                }
                System.out.println(order.getOrderIdString());
            }
            result.setData(orders);
            result.setStatusCode("200");
        }else{
            return Result.fail("未查询到当前用户的订单");
        }
        return result;
    }
    @PostMapping("/updateStatus")
    public Result<?> updateStatus(@RequestBody Map<String, Object> payload){
        Long orderId = Long.parseLong(payload.get("orderId").toString());
        String status =payload.get("status").toString();
        System.out.println("订单状态"+orderId);
        if(orderService.updateOrderStatus(orderId,status)){
            return Result.success("订单状态更新成功!");
        }else{
            return Result.fail("订单状态更新失败!");
        }

    }
}
